package awk.jdk8;

import awk.thread.ThreadPoolUtils;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Semaphore;

/**
 * @description:
 * @author: wanghaifeng
 * @date: 2021/3/5
 */
public class SemaphoreTest {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(8);
        ExecutorService executor = ThreadPoolUtils.getPool();
        executor.execute(new Task(1, semaphore, 3));
        executor.execute(new Task(2, semaphore, 4));
        executor.execute(new Task(3, semaphore, 6));
        executor.shutdown();
    }

    static class Task implements Runnable {
        private int id;
        private Semaphore semaphore;
        private int permit;

        public Task(int id, Semaphore semaphore, int permit) {
            this.id = id;
            this.semaphore = semaphore;
            this.permit = permit;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire(permit);
                System.out.println("Task " + id + " acquire " + permit + " semaphore");
                Thread.sleep(1000 + new Random().nextInt(1000));
                semaphore.release(permit);
                System.out.println("Task " + id + " release " + permit + " semaphore");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
